package generic.spread;

import generic.Subscriber;
import java.net.*;
import java.io.IOException;
import spread.*;

public class SpreadSubscriber {
	private Subscriber subscriber;
	private SpreadConnection connection = new SpreadConnection();
	private SpreadGroup group = new SpreadGroup();

	public SpreadSubscriber(Subscriber subscriber) {
		super();
		this.subscriber = subscriber;
		try{
			InetAddress addr = InetAddress.getByName("localhost");
			
			System.out.println("Connecting to daemon :" + addr  );
			connection.connect( addr , 0, "Subscriber", false, false);
		
			group.join(connection, "group");
			System.out.println("Ready to receive group : " + group.toString() );
			System.out.println("SpreadSubscriber waiting for messages...");
			run(); // We just use main thread for message waiting.
		}
		catch( Exception e )
		{
			e.printStackTrace();
		}
	}

    public void run() {
		try{
			while(true)
			{
				SpreadMessage message = connection.receive();
				if( message.isRegular() )
				{
					subscriber.receive((String)message.getObject());
				}
				else
					System.out.println("Membership message from " + message.getMembershipInfo().getGroup() + " : " + message.toString() );
			}
		}catch( Exception e )
		{
			e.printStackTrace();
		}
    }
}
